package com.ysd.lis.service.cri.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.cri.CriticalValReportDto;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.cri.CriCriticalReport;
import com.ysd.lis.entity.cri.CriUserVsDept;
import com.ysd.lis.entity.cri.CriWarningConfig;
import com.ysd.lis.entity.lab.LabCriticalReport;
import com.ysd.lis.entity.lab.LabSampleType;
import com.ysd.lis.mapper.cri.CriCriticalReportMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.cri.CriBiQuery;
import com.ysd.lis.request.cri.CriDeptSumQuery;
import com.ysd.lis.request.cri.CriticalSendMess;
import com.ysd.lis.service.SysOrgDepartmentService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.cri.CriCriticalReportService;
import com.ysd.lis.service.cri.CriUserVsDeptService;
import com.ysd.lis.service.cri.CriWarningConfigService;
import com.ysd.lis.socket.MessageTemplate;
import com.ysd.lis.socket.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wanghuaixing
 * @since 2025-02-13
 */
@Service
@Slf4j
public class CriCriticalReportServiceImpl extends ServiceImpl<CriCriticalReportMapper, CriCriticalReport> implements CriCriticalReportService {

    @Autowired
    CriCriticalReportMapper criticalReportMapper;
    @Autowired
    private CriWarningConfigService warningConfigService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgDepartmentService sysOrgDepartmentService;
    @Autowired
    private CriUserVsDeptService criUserVsDeptService;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Override
    public Result findCriticalReportInfo(CriticalValReportDto criticalReportDto) {
        MPJLambdaWrapper<CriCriticalReport> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(CriCriticalReport.class);
        queryWrapper.selectAs("u", PubEmployee::getName, CriCriticalReport::getDoctorPersonName);
        queryWrapper.leftJoin(PubEmployee.class, "u", p -> p.eq(PubEmployee::getCode, CriCriticalReport::getDoctorPerson).eq(PubEmployee::getDelFlag, 0));
        if (StringUtils.isNotEmpty(criticalReportDto.getNoticeDateStart()) && StringUtils.isNotEmpty(criticalReportDto.getNoticeDateEnd())) {
            Timestamp startTime = Timestamp.valueOf(criticalReportDto.getNoticeDateStart());
            Timestamp endTime = Timestamp.valueOf(criticalReportDto.getNoticeDateEnd());
            queryWrapper.ge(CriCriticalReport::getReportTime, startTime);
            queryWrapper.le(CriCriticalReport::getReportTime, endTime);
        }
        queryWrapper.eq(CriCriticalReport::getDelFlag, 0);
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getId()), CriCriticalReport::getId, criticalReportDto.getId());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getOrgId()), CriCriticalReport::getOrgId, criticalReportDto.getOrgId());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getItemNo()), CriCriticalReport::getItemNo, criticalReportDto.getItemNo());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getReqDept()), CriCriticalReport::getReportDeptNo, criticalReportDto.getReqDept());

        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatNo()), CriCriticalReport::getPatNo, criticalReportDto.getPatNo());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatNa()), CriCriticalReport::getPatNa, criticalReportDto.getPatNa());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatType()), CriCriticalReport::getPatNa, criticalReportDto.getPatType());

        if (Objects.nonNull(criticalReportDto.getStateCode())) {
            if (criticalReportDto.getStateCode() == 1) {
                queryWrapper.eq(CriCriticalReport::getStateCode, 30);
            }
            if (criticalReportDto.getStateCode() == 2) {
                queryWrapper.and(p -> p.ne(CriCriticalReport::getStateCode, 30).or().isNull(CriCriticalReport::getStateCode));
            }
        }
        List<CriCriticalReport> criCriticalReports = criticalReportMapper.selectList(queryWrapper);
        for (CriCriticalReport criCriticalReport : criCriticalReports) {
            String itemException = "患者%s (%s) 出现危急值! %s(%s):%s。";
            String result = String.format(itemException, criCriticalReport.getPatNa(), criCriticalReport.getPatNo(), criCriticalReport.getItemNa(), criCriticalReport.getItemNo(), criCriticalReport.getReportVal());
            criCriticalReport.setItemException(result);
        }
        return Result.succ(criCriticalReports);
    }

    @Override
    public Result nurseChk(CriCriticalReport riticalReportParam) {
        if (StringUtils.isBlank(riticalReportParam.getNursePerson())) {
            return Result.fail("请上传护士编号");
        }
        List<CriWarningConfig> warningConfigs = warningConfigService.list(new LambdaQueryWrapper<CriWarningConfig>().eq(CriWarningConfig::getDelFlag, 0));
        Map<String, List<String>> macUrlMap = warningConfigs.stream()
                .collect(Collectors.groupingBy(CriWarningConfig::getUserInfo,
                        Collectors.mapping(CriWarningConfig::getMacUrl, Collectors.toList())));

        CriCriticalReport criticalReport = criticalReportMapper.selectById(riticalReportParam.getId());
        // 通知给护士状态
        if (criticalReport.getStateCode() != 10) {
            return Result.fail("当前危急值已处理");
        } else {
            // 通知医生
            List<SysUser> macUrlAllByDept = getDoctorMacUrlAllByDept(criticalReport.getReportDeptNo());
            List<SysUser> nurseAllByDept = getNurseMacUrlAllByDept(criticalReport.getReportDeptNo());
            if (CollectionUtil.isNotEmpty(macUrlAllByDept)) {
                // 推送websocket
                MessageTemplate messageTemplate = new MessageTemplate();
                // 类型为2是推送,3是销毁
                messageTemplate.setType("2");
                CriticalSendMess criticalSendMess = new CriticalSendMess();
                BeanUtil.copyProperties(criticalReport, criticalSendMess);
                messageTemplate.setMessage(String.valueOf(criticalSendMess));
                // 根据被通知人编号 查询全科室的用户
                boolean havaUserInfo = false;
                for (SysUser sysUser : macUrlAllByDept) {
                    List<String> macUrlList = macUrlMap.get(sysUser.getUsername());
                    if (CollectionUtil.isNotEmpty(macUrlList)) {
                        havaUserInfo = true;
                        for (String macUrl : macUrlList) {
                            WebSocketUtils.sendMessage(macUrl, messageTemplate);
                        }
                    } else {
                        log.error("[{}]用户没有配置mac地址", sysUser.getUsername() + ":" + sysUser.getRealname());
                    }
                }
                if (!havaUserInfo) {
                    log.error("没有找到被通知医生,请维护医生的设备配置信息");
                    return Result.fail("没有找到被通知医生,请维护医生的设备配置信息");
                }
            } else {
                log.error("没有找到被通知医生");
                return Result.fail("没有找到被通知医生");
            }
            for (SysUser sysUser : nurseAllByDept) {
                List<String> macUrlList = macUrlMap.get(sysUser.getUsername());
                // 推送websocket
                MessageTemplate messageTemplate = new MessageTemplate();
                // 类型为2是推送,3是销毁
                messageTemplate.setType("3");
                CriticalSendMess criticalSendMess = new CriticalSendMess();
                BeanUtil.copyProperties(criticalReport, criticalSendMess);
                messageTemplate.setMessage(String.valueOf(criticalSendMess));
                if (CollectionUtil.isNotEmpty(macUrlList)) {
                    for (String macUrl : macUrlList) {
                        WebSocketUtils.sendMessage(macUrl, messageTemplate);
                    }
                } else {
                    log.error("[{}]用户没有配置mac地址", sysUser.getUsername() + ":" + sysUser.getRealname());
                }
            }
            criticalReport.setNursePerson(riticalReportParam.getNursePerson());
            criticalReport.setStateCode(20);
            criticalReport.setNurseTime(new Timestamp(System.currentTimeMillis()));
            criticalReport.setDoctorPerson(riticalReportParam.getDoctorPerson());
            criticalReport.setDoctorReportTime(new Timestamp(System.currentTimeMillis()));
            criticalReportMapper.updateById(criticalReport);
            return Result.succ("处理成功");

        }
    }

    @Override
    public Result criticalReportChk(CriCriticalReport criticalReportParm) {
        // TODO 发送消息接口平台,返回信息成功之后,再调用websocket 进行通知取消弹窗
        // 获取用户预警配置(mac地址)
        List<CriWarningConfig> warningConfigs = warningConfigService.list(new LambdaQueryWrapper<CriWarningConfig>().eq(CriWarningConfig::getDelFlag, 0));
        Map<String, List<String>> macUrlMap = warningConfigs.stream()
                .collect(Collectors.groupingBy(CriWarningConfig::getUserInfo,
                        Collectors.mapping(CriWarningConfig::getMacUrl, Collectors.toList())));

        CriCriticalReport criticalReport = this.getById(criticalReportParm.getId());
        if (criticalReport.getStateCode() == 30) {
            return Result.fail("当前危急值已审核");
        } else {
            // 推送websocket
            MessageTemplate messageTemplate = new MessageTemplate();
            // 类型为2是推送,3是销毁
            messageTemplate.setType("3");
            CriticalSendMess criticalSendMess = new CriticalSendMess();
            BeanUtil.copyProperties(criticalReport, criticalSendMess);
            messageTemplate.setMessage(String.valueOf(criticalSendMess));
            // 根据通知医生编号,有通知,没有通知全科室的医生
            List<SysUser> macUrlAllByDept = getDoctorMacUrlAllByDept(criticalReport.getReportDeptNo());
            if (CollectionUtil.isNotEmpty(macUrlAllByDept)) {
                // 根据被通知人编号 查询全科室的用户
                boolean havaUserInfo = false;
                for (SysUser sysUser : macUrlAllByDept) {
                    List<String> macUrlList = macUrlMap.get(sysUser.getUsername());
                    if (CollectionUtils.isNotEmpty(macUrlList)) {
                        havaUserInfo = true;
                        for (String macUrl : macUrlList) {
                            WebSocketUtils.sendMessage(macUrl, messageTemplate);
                        }
                    } else {
                        log.error("[{}]用户没有配置mac地址", sysUser.getUsername() + ":" + sysUser.getRealname());
                    }
                }
                if (!havaUserInfo) {
                    log.error("没有找到被通知医生,请维护医生的设备配置信息");
                    return Result.fail("没有找到被通知医生,请维护医生的设备配置信息");
                }
            } else {
                log.error("没有找到被通知医生");
                return Result.fail("没有找到被通知医生");
            }
            criticalReport.setStateCode(30);
            criticalReport.setReviewerTime(new Timestamp(System.currentTimeMillis()));
            criticalReport.setReviewerDoctor(criticalReportParm.getReviewerDoctor());
            criticalReport.setTreatmentMeasure(criticalReportParm.getTreatmentMeasure());
            criticalReport.setDoctorPerson(criticalReportParm.getDoctorPerson());
            this.updateById(criticalReport);

            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

            try {
                if (CollectionUtils.isNotEmpty(collect)) {
                    for (String webUrl : collect) {
                        LabCriticalReport q = new LabCriticalReport();
                        q.setCriticalNo(criticalReport.getCriticalNo());
                        q.setReviewerTime(criticalReport.getReviewerTime());
                        q.setReviewerDoctor(criticalReport.getReviewerDoctor());
                        q.setTreatmentMeasure(criticalReport.getTreatmentMeasure());
                       // q.setOrgId(orgId);

                        webUrl = webUrl.substring(0, webUrl.lastIndexOf("/"));

                        String returnMsg = HttpUtil.createPost(webUrl + "/CriticalValuePost/PostInfoOurLis").body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().body();
                        JSONObject reportObject = new JSONObject(returnMsg);
                        JSONObject reportStatus = reportObject.getJSONObject("status");
                        String reportCode = reportStatus.get("code").toString();
                        if ("400".equals(reportCode)) {
                            return Result.fail("接口管理平台异常,请检查");
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("接口管理平台异常,请检查");
            }

            return Result.succ(1, "审核成功", criticalReport);
        }
    }

    @Override
    public Result getCriticalReport(String isChk, String userCode, String type) {

        MPJLambdaWrapper<CriUserVsDept> lambdaWrapper = new MPJLambdaWrapper();
        lambdaWrapper.selectAll(CriUserVsDept.class);
        lambdaWrapper.eq(CriUserVsDept::getUsername, userCode);
        lambdaWrapper.eq(CriUserVsDept::getDelFlag, 0);
        List<CriUserVsDept> list = criUserVsDeptService.list(lambdaWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> deptCode = list.stream().map(CriUserVsDept::getDeptCode).collect(Collectors.toList());
            LambdaQueryWrapper<CriCriticalReport> queryWrapper = new LambdaQueryWrapper<>();

            if ("0".equals(type)) {
                if ("0".equals(isChk)) {
                    queryWrapper.eq(CriCriticalReport::getStateCode, 10);
                } else {
                    queryWrapper.gt(CriCriticalReport::getStateCode, 10);
                }
            } else {
                if ("0".equals(isChk)) {
                    queryWrapper.eq(CriCriticalReport::getStateCode, 20);
                } else {
                    queryWrapper.gt(CriCriticalReport::getStateCode, 20);
                }
            }
            queryWrapper.eq(CriCriticalReport::getDelFlag, 0);
            queryWrapper.in(CriCriticalReport::getReportDeptNo, deptCode);
            // return Result.succ(criticalReportMapper.selectList(queryWrapper));
            List<CriCriticalReport> criCriticalReports = criticalReportMapper.selectList(queryWrapper);
            for (CriCriticalReport criCriticalReport : criCriticalReports) {
                String itemException = "患者%s (%s) 出现危急值! %s(%s):%s。";
                String result = String.format(itemException, criCriticalReport.getPatNa(), criCriticalReport.getPatNo(), criCriticalReport.getItemNa(), criCriticalReport.getItemNo(), criCriticalReport.getReportVal());
                criCriticalReport.setItemException(result);
            }
            return Result.succ(criCriticalReports);
        } else {
            return Result.succ(null);
        }
    }

    @Override
    public Result getDoctorByDept(CriCriticalReport riticalReportParam) {

        List<SysUser> macUrlAllByDept = getDoctorMacUrlAllByDept(riticalReportParam.getReportDeptNo());

        return Result.succ(macUrlAllByDept);
    }

    @Override
    public Result findNotReceCriticaltInfo(CriticalValReportDto criticalReportDto) {
        LambdaQueryWrapper<CriCriticalReport> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(criticalReportDto.getNoticeDateStart()) && StringUtils.isNotEmpty(criticalReportDto.getNoticeDateEnd())) {
            Timestamp startTime = Timestamp.valueOf(criticalReportDto.getNoticeDateStart());
            Timestamp endTime = Timestamp.valueOf(criticalReportDto.getNoticeDateEnd());
            queryWrapper.ge(CriCriticalReport::getReportTime, startTime);
            queryWrapper.le(CriCriticalReport::getReportTime, endTime);
        }
        queryWrapper.eq(CriCriticalReport::getDelFlag, 0);
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getId()), CriCriticalReport::getId, criticalReportDto.getId());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getOrgId()), CriCriticalReport::getOrgId, criticalReportDto.getOrgId());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getItemNo()), CriCriticalReport::getItemNo, criticalReportDto.getItemNo());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getReqDept()), CriCriticalReport::getReportDeptNo, criticalReportDto.getReqDept());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatNo()), CriCriticalReport::getPatNo, criticalReportDto.getPatNo());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatNa()), CriCriticalReport::getPatNa, criticalReportDto.getPatNa());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatType()), CriCriticalReport::getPatNa, criticalReportDto.getPatType());
        queryWrapper.and(item -> item.eq(CriCriticalReport::getStateCode, 10).or().isNull(CriCriticalReport::getStateCode));
        List<CriCriticalReport> criCriticalReports = criticalReportMapper.selectList(queryWrapper);
        for (CriCriticalReport criCriticalReport : criCriticalReports) {
            String itemException = "患者%s (%s) 出现危急值! %s(%s):%s。";
            String result = String.format(itemException, criCriticalReport.getPatNa(), criCriticalReport.getPatNo(), criCriticalReport.getItemNa(), criCriticalReport.getItemNo(), criCriticalReport.getReportVal());
            criCriticalReport.setItemException(result);
        }
        return Result.succ(criCriticalReports);
    }

    @Override
    public Result findUntreatedCriticaltInfo(CriticalValReportDto criticalReportDto) {
        LambdaQueryWrapper<CriCriticalReport> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(criticalReportDto.getNoticeDateStart()) && StringUtils.isNotEmpty(criticalReportDto.getNoticeDateEnd())) {
            Timestamp startTime = Timestamp.valueOf(criticalReportDto.getNoticeDateStart());
            Timestamp endTime = Timestamp.valueOf(criticalReportDto.getNoticeDateEnd());
            queryWrapper.ge(CriCriticalReport::getReportTime, startTime);
            queryWrapper.le(CriCriticalReport::getReportTime, endTime);
        }
        queryWrapper.eq(CriCriticalReport::getDelFlag, 0);
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getId()), CriCriticalReport::getId, criticalReportDto.getId());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getOrgId()), CriCriticalReport::getOrgId, criticalReportDto.getOrgId());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getItemNo()), CriCriticalReport::getItemNo, criticalReportDto.getItemNo());
        queryWrapper.eq(StringUtils.isNotBlank(criticalReportDto.getReqDept()), CriCriticalReport::getReportDeptNo, criticalReportDto.getReqDept());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatNo()), CriCriticalReport::getPatNo, criticalReportDto.getPatNo());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatNa()), CriCriticalReport::getPatNa, criticalReportDto.getPatNa());
        queryWrapper.like(StringUtils.isNotBlank(criticalReportDto.getPatType()), CriCriticalReport::getPatNa, criticalReportDto.getPatType());
        queryWrapper.eq(CriCriticalReport::getStateCode, 20);

        List<CriCriticalReport> criCriticalReports = criticalReportMapper.selectList(queryWrapper);
        for (CriCriticalReport criCriticalReport : criCriticalReports) {
            String itemException = "患者%s (%s) 出现危急值! %s(%s):%s。";
            String result = String.format(itemException, criCriticalReport.getPatNa(), criCriticalReport.getPatNo(), criCriticalReport.getItemNa(), criCriticalReport.getItemNo(), criCriticalReport.getReportVal());
            criCriticalReport.setItemException(result);
        }
        return Result.succ(criCriticalReports);
    }

    public List<SysUser> getDoctorMacUrlAll(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return null;
        }
        MPJLambdaWrapper<SysOrgDepartment> lambdaWrapper = new MPJLambdaWrapper();
        lambdaWrapper.selectAll(SysOrgDepartment.class);
        lambdaWrapper.leftJoin(SysUserDept.class, item -> item.eq(SysUserDept::getDeptId, SysOrgDepartment::getId).eq(SysUserDept::getDelFlag, 0));
        lambdaWrapper.leftJoin(SysUser.class, item -> item.eq(SysUser::getId, SysUserDept::getUserId).eq(SysUser::getDelFlag, 0));
        lambdaWrapper.eq(SysUser::getUsername, userCode);
        lambdaWrapper.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> list = sysOrgDepartmentService.list(lambdaWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            SysOrgDepartment sysOrgDepartment = list.get(0);
            MPJLambdaWrapper<SysUser> mpjLambdaWrapper = new MPJLambdaWrapper();
            mpjLambdaWrapper.selectAll(SysUser.class);
            mpjLambdaWrapper.leftJoin(SysUserDept.class, p -> p.eq(SysUserDept::getUserId, SysUser::getId).eq(SysUserDept::getDelFlag, 0));
            mpjLambdaWrapper.leftJoin(SysUserRole.class, p -> p.eq(SysUserRole::getUserId, SysUser::getId).eq(SysUserRole::getDelFlag, 0));
            mpjLambdaWrapper.leftJoin(SysRole.class, p -> p.eq(SysUserRole::getRoleId, SysRole::getId).eq(SysRole::getDelFlag, 0));
            mpjLambdaWrapper.eq(SysUserDept::getDeptId, sysOrgDepartment.getId());
            mpjLambdaWrapper.eq(SysRole::getRoleName, "医生");
            List<SysUser> userList = sysUserService.list(mpjLambdaWrapper);
            return userList;
        }

        return null;
    }

    public List<SysUser> getDoctorMacUrlAllByDept(String deptCode) {
        MPJLambdaWrapper<SysUser> mpjLambdaWrapper = new MPJLambdaWrapper();
        mpjLambdaWrapper.distinct();
        mpjLambdaWrapper.selectAll(SysUser.class);
        mpjLambdaWrapper.leftJoin(CriUserVsDept.class, p -> p.eq(CriUserVsDept::getUsername, SysUser::getUsername).eq(CriUserVsDept::getDelFlag, 0));
        mpjLambdaWrapper.eq(CriUserVsDept::getDeptCode, deptCode);
        List<SysUser> userList = sysUserService.list(mpjLambdaWrapper);
        return userList;
    }

    public List<SysUser> getNurseMacUrlAllByDept(String deptCode) {
        if (StringUtils.isBlank(deptCode)) {
            log.error("上报危急值没有科室信息");
            return null;
        }
        LambdaQueryWrapper<SysOrgDepartment> lambdaWrapper = new LambdaQueryWrapper();
        lambdaWrapper.eq(SysOrgDepartment::getCode, deptCode);
        lambdaWrapper.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> list = sysOrgDepartmentService.list(lambdaWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            SysOrgDepartment sysOrgDepartment = list.get(0);
            MPJLambdaWrapper<SysUser> mpjLambdaWrapper = new MPJLambdaWrapper();
            mpjLambdaWrapper.selectAll(SysUser.class);
            mpjLambdaWrapper.leftJoin(SysUserDept.class, p -> p.eq(SysUserDept::getUserId, SysUser::getId).eq(SysUserDept::getDelFlag, 0));
            mpjLambdaWrapper.leftJoin(SysUserRole.class, p -> p.eq(SysUserRole::getUserId, SysUser::getId).eq(SysUserRole::getDelFlag, 0));
            mpjLambdaWrapper.leftJoin(SysRole.class, p -> p.eq(SysUserRole::getRoleId, SysRole::getId).eq(SysRole::getDelFlag, 0));
            mpjLambdaWrapper.eq(SysUserDept::getDeptId, sysOrgDepartment.getId());
            mpjLambdaWrapper.eq(SysRole::getRoleName, "护士");
            List<SysUser> userList = sysUserService.list(mpjLambdaWrapper);
            return userList;
        }

        return null;
    }

    /**
     * 处置科室分布
     *
     * @return
     */
    @Override
    public Result deptSumQuery() {
        // 查询所有科室
        LambdaQueryWrapper<SysOrgDepartment> lambdaWrapper = new LambdaQueryWrapper();
        lambdaWrapper.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> deptList = sysOrgDepartmentService.list(lambdaWrapper);
        // deptList里数据 key为code value为name 放到map
        Map<String, String> deptMap = deptList.stream().collect(Collectors.toMap(SysOrgDepartment::getCode, SysOrgDepartment::getName));

        // 循环map
        List<CriDeptSumQuery> deptSumQueryList = new ArrayList<>();
        List<String> deptNaList = new ArrayList<>();
        List<Integer> unConfirmedList = new ArrayList<>();
        List<Integer> unReceiveList = new ArrayList<>();
        List<Integer> unHandleList = new ArrayList<>();
        List<Integer> handleList = new ArrayList<>();

        List<CriCriticalReport> criCriticalReports = criticalReportMapper.selectList(new LambdaQueryWrapper<CriCriticalReport>().eq(CriCriticalReport::getDelFlag, 0));
        // 根据reportDeptNo进行分组
        if (CollectionUtil.isNotEmpty(criCriticalReports)) {
            Map<String, List<CriCriticalReport>> listMapByDeptNo = criCriticalReports.stream().collect(Collectors.groupingBy(CriCriticalReport::getReportDeptNo));
            // 循环map
            for (Map.Entry<String, List<CriCriticalReport>> entry : listMapByDeptNo.entrySet()) {
                String deptNo = entry.getKey();
                List<CriCriticalReport> criticalReports = entry.getValue();
                List<CriCriticalReport> chkList = criticalReports.stream().filter(a -> a.getStateCode() == 30).collect(Collectors.toList());
                // 求平均处置时间

                // 计算平均处置时间
                double totalHandleTime = 0;
                int handleCount = 0;
                for (CriCriticalReport report : chkList) {
                    if (report.getReviewerTime() != null && report.getDoctorReportTime() != null) {
                        long diffInMillis = report.getReviewerTime().getTime() - report.getDoctorReportTime().getTime();
                        double diffInMinutes = diffInMillis / (60.0 * 1000.0);
                        totalHandleTime += diffInMinutes;
                        handleCount++;
                    }
                }
                double avgHandleTime = handleCount > 0 ? totalHandleTime / handleCount : 0;
                // 使用 BigDecimal 保留两位小数
                BigDecimal avgHandleTimeBD = new BigDecimal(avgHandleTime).setScale(2, RoundingMode.HALF_UP);
                avgHandleTime = avgHandleTimeBD.doubleValue();

                deptNaList.add(deptMap.get(deptNo));
                // 统计未确认数量stateCode状态码为0
                Integer unConfirmedCnt = Math.toIntExact(criticalReports.stream().filter(a -> a.getStateCode() == 0).count());
                unConfirmedList.add(unConfirmedCnt);
                Integer unReceiveCnt = Math.toIntExact(criticalReports.stream().filter(a -> a.getStateCode() == 10).count());
                unReceiveList.add(unReceiveCnt);
                Integer unHandleCnt = Math.toIntExact(criticalReports.stream().filter(a -> a.getStateCode() == 20).count());
                unHandleList.add(unHandleCnt);
                Integer handleCnt = Math.toIntExact(criticalReports.stream().filter(a -> a.getStateCode() == 30).count());
                handleList.add(handleCnt);
                CriDeptSumQuery criDeptSumQuery = new CriDeptSumQuery();
                deptNaList.add(deptMap.get(deptNo));
                criDeptSumQuery.setDeptNa(deptMap.get(deptNo));
                criDeptSumQuery.setUnConfirmed(unConfirmedCnt);
                criDeptSumQuery.setUnReceive(unReceiveCnt);
                criDeptSumQuery.setUnHandle(unHandleCnt);
                criDeptSumQuery.setHandle(handleCnt);
                criDeptSumQuery.setAvgHandleTime(avgHandleTime);
                if (unHandleCnt + handleCnt == 0) {
                    criDeptSumQuery.setHandleRate(100 + "%");
                } else {
                    int useNum = (int) ((handleCnt * 1.0 / (unHandleCnt + handleCnt)) * 100);
                    criDeptSumQuery.setHandleRate(useNum + "%");
                }
                deptSumQueryList.add(criDeptSumQuery);
            }
        }

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("data", deptSumQueryList);
        dataMap.put("deptNaList", deptNaList);
        dataMap.put("unConfirmedList", unConfirmedList);
        dataMap.put("unReceiveList", unReceiveList);
        dataMap.put("unHandleList", unHandleList);
        dataMap.put("handleList", handleList);
        return Result.succ(dataMap);
    }

    @Override
    public Result getBIData() {

        // 中间处置数据
        List<CriCriticalReport> criCriticalReports = criticalReportMapper.selectList(new LambdaQueryWrapper<CriCriticalReport>().eq(CriCriticalReport::getDelFlag, 0));
        Integer sumChkData = Math.toIntExact(criCriticalReports.stream().filter(a -> a.getStateCode() >= 20).count());
        Integer noChkData = Math.toIntExact(criCriticalReports.stream().filter(a -> a.getStateCode() == 20).count());
        Integer chkData = Math.toIntExact(criCriticalReports.stream().filter(a -> a.getStateCode() == 30).count());
        Integer chkRate = 0;
        if (sumChkData == 0) {
            chkRate = 100;
        } else {
            int useNum = (int) ((chkData * 1.0 / sumChkData) * 100);
            chkRate = useNum;
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf1.format(new Date());
        Timestamp startTime = Timestamp.valueOf(format + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(format + " 23:59:59");
        // 危急值监控
        List<CriCriticalReport> criticalReportToday = criticalReportMapper.selectList(new LambdaQueryWrapper<CriCriticalReport>().ge(CriCriticalReport::getCreateTime, startTime).le(CriCriticalReport::getCreateTime, endTime).eq(CriCriticalReport::getDelFlag, 0));
        Integer sumData = criticalReportToday.size();
        Integer unConfirmedCnt = Math.toIntExact(criticalReportToday.stream().filter(a -> a.getStateCode() == 0).count());
        Integer unReceiveCnt = Math.toIntExact(criticalReportToday.stream().filter(a -> a.getStateCode() == 10).count());
        Integer unHandleCnt = Math.toIntExact(criticalReportToday.stream().filter(a -> a.getStateCode() == 20).count());
        Integer handleCnt = Math.toIntExact(criticalReportToday.stream().filter(a -> a.getStateCode() == 30).count());
        // 科室处置统计
        List<String> deptNaList = new ArrayList<>();
        List<Integer> deptChkDataList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(criCriticalReports)) {
            // 查询所有科室
            List<CriCriticalReport> collect = criCriticalReports.stream().filter(p -> p.getStateCode() == 30).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                LambdaQueryWrapper<SysOrgDepartment> lambdaWrapper = new LambdaQueryWrapper();
                lambdaWrapper.eq(SysOrgDepartment::getDelFlag, 0);
                List<SysOrgDepartment> deptList = sysOrgDepartmentService.list(lambdaWrapper);
                Map<String, String> deptMap = deptList.stream().collect(Collectors.toMap(SysOrgDepartment::getCode, SysOrgDepartment::getName));

                Map<String, List<CriCriticalReport>> listMapByDeptNo = collect.stream().collect(Collectors.groupingBy(CriCriticalReport::getReportDeptNo));
                for (Map.Entry<String, List<CriCriticalReport>> entry : listMapByDeptNo.entrySet()) {
                    String deptNo = entry.getKey();
                    deptNaList.add(deptMap.get(deptNo));
                    deptChkDataList.add(entry.getValue().size());
                }
            }
        }

        CriBiQuery criBiQuery = new CriBiQuery();
        criBiQuery.setSumChkData(sumChkData);
        criBiQuery.setNoChkData(noChkData);
        criBiQuery.setChkData(chkData);
        criBiQuery.setChkRate(chkRate);
        criBiQuery.setSumData(sumData);
        criBiQuery.setUnConfirmedCnt(unConfirmedCnt);
        criBiQuery.setUnReceiveCnt(unReceiveCnt);
        criBiQuery.setUnHandleCnt(unHandleCnt);
        criBiQuery.setHandleCnt(handleCnt);
        criBiQuery.setDeptNaList(deptNaList);
        criBiQuery.setDeptChkDataList(deptChkDataList);

        return Result.succ(criBiQuery);
    }

    @Override
    public Result getLargeScreenData() {
        List<CriCriticalReport> criticalReportToday = criticalReportMapper.selectList(new LambdaQueryWrapper<CriCriticalReport>().eq(CriCriticalReport::getDelFlag, 0));
        for (CriCriticalReport criCriticalReport : criticalReportToday) {
            String itemException = "患者%s (%s) 出现危急值! %s(%s):%s。";
            String result = String.format(itemException, criCriticalReport.getPatNa(), criCriticalReport.getPatNo(), criCriticalReport.getItemNa(), criCriticalReport.getItemNo(), criCriticalReport.getReportVal());
            criCriticalReport.setItemException(result);
            switch (criCriticalReport.getStateCode()) {
                case 0:
                    criCriticalReport.setStateNa("未发布");
                    break;
                case 10:
                    criCriticalReport.setStateNa("未接收");
                    break;
                case 20:
                    criCriticalReport.setStateNa("未处置");
                    break;
                case 30:
                    criCriticalReport.setStateNa("已处置");
                    break;
                default:
                    criCriticalReport.setStateNa("未知");
                    break;
            }
        }
        return Result.succ(criticalReportToday);
    }
}
